package com.xkw.demo.config.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 访问网站时，未登录者需要先进行登录操作的登录过滤器实例
 */
//@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")单独使用没有FilterConfig时放开此注解
public class LoginFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 获取请求的uri
		String uri = request.getRequestURI();
		// 获取容器路径
		String ctxPath = request.getContextPath();

		// 资源文件不过滤: 以.js|css|png|jpg|jpeg|gif|ico|woff结尾的
		if (uri.matches(".+\\.(html|js|css|png|jpg|jpeg|gif|ico|ttf|woff|woff2)$")) {
			filterChain.doFilter(request, response);
			return;
		}

		// 登录请求、验证登录的请求不过滤
		if (uri.startsWith(ctxPath + "/admin/login") || uri.startsWith("/admin/checkLogin")) {
			filterChain.doFilter(request, response);
			return;
		}

		// 否则执行过滤:未登录者须先前往登录界面登录
		Object obj = request.getSession().getAttribute("user");
		if (null == obj) {
			filterChain.doFilter(request, response);
			//response.sendRedirect(ctxPath + "/admin/login");正常登录情况放开此行注释上一行
		} else {
			filterChain.doFilter(request, response);
		}

	}

}
